package com.sniff.atp.modules.test.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ckbs.global.common.utils.CopyUtils;
import com.sniff.atp.dto.ContentDTO;
import com.sniff.atp.modules.test.mapper.OpsMembershipChangeMapper;
import com.sniff.atp.modules.test.model.OpsMembershipChange;
import com.sniff.atp.modules.test.model.OpsMembershipChangeLog;
import com.sniff.atp.modules.test.model.OpsMembershipInfo;
import com.sniff.atp.modules.test.service.OpsMembershipChangeLogService;
import com.sniff.atp.modules.test.service.OpsMembershipChangeService;
import com.sniff.atp.service.login.ClientLoginService;
import com.sniff.atp.utils.DBUtil;
import com.sniff.atp.utils.HttpClientUtil;
import com.sniff.atp.utils.JsonUtil;
import com.sniff.atp.utils.ToolsUtil;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 赠送会员 服务实现类
 * </p>
 *
 * @author macro
 * @since 2023-12-12
 */
@Service
public class OpsMembershipChangeServiceImpl extends ServiceImpl<OpsMembershipChangeMapper, OpsMembershipChange> implements OpsMembershipChangeService {

    @Autowired
    private OpsMembershipChangeLogService opsMembershipChangeLogService;

    @Autowired
    private OpsMembershipChangeMapper opsMembershipChangeMapper;

    @Autowired
    private ClientLoginService clientLoginService;

    @Value("${sniff.wms.username}")
    private String systemUsername;
    @Value("${sniff.wms.password}")
    private String systemPassword;

    @Override
    public boolean create(OpsMembershipChange opsMembershipChange)  {

        try {
            //请求充值接口
            //登录
            JSONObject param = new JSONObject();
            param.put("autoRecharge", 0);
            param.put("customerId", opsMembershipChange.getCustomerId());
            param.put("superCustomerId", opsMembershipChange.getSuperCustomerId());
            param.put("day", opsMembershipChange.getDay());
            param.put("membershipTemplateId", opsMembershipChange.getMembershipTemplateId());
            param.put("membershipTemplatePriceId", opsMembershipChange.getMembershipTemplatePriceId());
            param.put("orderType", 0);

            String result = new HttpClientUtil().doPostNeedToken("https://gateway-prod.theckb.com/settlement/wallet/recharge/membership/manualByManager", param);
            String code = JsonUtil.extractString(result, "code");
            if("0".equals(code)){
                opsMembershipChange.setStatus("成功");
                //如果请求成功过，先等待5秒，等结果，从库数据，同步没有那么快
                ToolsUtil.sleep(3000);
            }else{
                opsMembershipChange.setStatus("失败");
            }

            List<JSONObject> select = DBUtil.select("prod-customer-查询指定用户会员等级信息", new ContentDTO("superCustomerId", opsMembershipChange.getSuperCustomerId().toString()));
            for (JSONObject o: select) {
                String membershipTemplateNameFinal = o.getString("membershipTemplateNameFinal");
                String expiresDateFinal = o.getString("expiresDateFinal");
                opsMembershipChange.setMembershipTemplateNameFinal(membershipTemplateNameFinal);

//                日期格式转换
                String format = "yyyy-MM-dd";
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                Date date = null;
                try {
                    date = sdf.parse(expiresDateFinal);
                    System.out.println(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                opsMembershipChange.setExpiresDateFinal(date);
                opsMembershipChange.setMembershipTemplateNameFinal(membershipTemplateNameFinal);
            }

            //保存数据
            opsMembershipChange.setCreateTime(new Date());
            opsMembershipChange.setUpdateTime(new Date());
            boolean saveFlag = save(opsMembershipChange);


            //增加日志
            OpsMembershipChangeLog opsMembershipChangeLog = new OpsMembershipChangeLog();
            CopyUtils.copyObject(opsMembershipChange,opsMembershipChangeLog);
            opsMembershipChangeLogService.save(opsMembershipChangeLog);

            return saveFlag;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean update(Long id, OpsMembershipChange opsMembershipChange) {
        opsMembershipChange.setUpdateTime(new Date());
        //获取更新的状态
        //增加日志
        OpsMembershipChangeLog opsMembershipChangeLog = new OpsMembershipChangeLog();
        CopyUtils.copyObject(opsMembershipChange,opsMembershipChangeLog);
        opsMembershipChange.setCreateTime(new Date());
        opsMembershipChangeLogService.save(opsMembershipChangeLog);

        return updateById(opsMembershipChange);
    }

    @Override
    public Page<OpsMembershipChange> list(OpsMembershipChange opsMembershipChange, Integer pageSize, Integer pageNum) {
        Page<OpsMembershipChange> page = new Page<>(pageNum, pageSize);
        QueryWrapper<OpsMembershipChange> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .like(StringUtil.isNotBlank(opsMembershipChange.getCustomerName()), OpsMembershipChange::getCustomerName,opsMembershipChange.getCustomerName())
                .like(opsMembershipChange.getOpsMembershipChangeId() != null,OpsMembershipChange::getOpsMembershipChangeId,opsMembershipChange.getOpsMembershipChangeId())
                .eq(StringUtil.isNotBlank(opsMembershipChange.getStatus()),OpsMembershipChange::getStatus,opsMembershipChange.getStatus())
                .eq(opsMembershipChange.getCustomerId() != null,OpsMembershipChange::getCustomerId,opsMembershipChange.getCustomerId())
                .eq(opsMembershipChange.getCustomerShopId() != null,OpsMembershipChange::getCustomerShopId,opsMembershipChange.getCustomerShopId())
                .ge(opsMembershipChange.getStartTime() != null,OpsMembershipChange::getCreateTime,opsMembershipChange.getStartTime())
                .le(opsMembershipChange.getEndTime() != null,OpsMembershipChange::getCreateTime,opsMembershipChange.getEndTime())
                .orderByDesc(OpsMembershipChange::getCreateTime);
        return page(page, wrapper);
    }


    @Override
    public OpsMembershipChange getCustomerInfo(OpsMembershipChange opsMembershipChange){


//        查询用户id
        List<JSONObject> select = DBUtil.select("prod-customer-查询用户基本信息", new ContentDTO("customerId", opsMembershipChange.getCustomerId().toString()));
        String customerStationCode = null;
        String membershipStationCode = null;
        opsMembershipChange.setCanSendFlag(false);
        for (JSONObject o: select) {
            String customerId = o.getString("customer_id");
            String superCustomerId = o.getString("super_customer_id");
            String unificationCustomerFullName = o.getString("unification_customer_full_name");
            customerStationCode = o.getString("station_code");
            opsMembershipChange.setCustomerId(Long.valueOf(customerId));
            opsMembershipChange.setSuperCustomerId(Long.valueOf(superCustomerId));
            opsMembershipChange.setCustomerName(unificationCustomerFullName);
            opsMembershipChange.setCustomerStationCode(customerStationCode);

        }
//                查询会员等级
        List<JSONObject> select2 = DBUtil.select("prod-customer-查询会员等级信息", new ContentDTO("membershipFee", opsMembershipChange.getMembershipFee().toString()));

        for (JSONObject o: select2) {
            String membershipTemplateId = o.getString("membership_template_id");
            String membershipTemplatePriceId = o.getString("membership_template_price_id");
            String priceName = o.getString("price_name");
            String discountActualPrice = o.getString("discount_actual_price");
//            opsMembershipChange.setMembershipTemplateId(Long.valueOf(membershipTemplateId));
            opsMembershipChange.setMembershipTemplateId(membershipTemplateId);
//            opsMembershipChange.setMembershipTemplatePriceId(Long.valueOf(membershipTemplatePriceId));
            opsMembershipChange.setMembershipTemplatePriceId(membershipTemplatePriceId);
            opsMembershipChange.setMembershipTemplatePriceName(priceName);
            opsMembershipChange.setMembershipTemplateName(priceName);
            membershipStationCode = o.getString("station_code");
        }
        //查询用户的站点和赠送会员的站点不一致，不支持赠送，报错
        if(membershipStationCode != null && customerStationCode != null && membershipStationCode.equals(customerStationCode)){
            opsMembershipChange.setCanSendFlag(true);
        }

        return opsMembershipChange;

    }

    @Override
    public OpsMembershipChange getMembershipInfo(OpsMembershipChange opsMembershipChange){

        List<JSONObject> select = DBUtil.select("prod-customer-查询用户基本信息", new ContentDTO("customerId", opsMembershipChange.getCustomerId().toString()));
        String customerStationCode = null;
        for (JSONObject o: select) {
            String customerId = o.getString("customer_id");
            String superCustomerId = o.getString("super_customer_id");
            String unificationCustomerFullName = o.getString("unification_customer_full_name");
            customerStationCode = o.getString("station_code");
            opsMembershipChange.setCustomerId(Long.valueOf(customerId));
            opsMembershipChange.setSuperCustomerId(Long.valueOf(superCustomerId));
            opsMembershipChange.setCustomerName(unificationCustomerFullName);
            opsMembershipChange.setCustomerStationCode(customerStationCode);

        }


        List<OpsMembershipInfo> membershipInfoList = new ArrayList<>();
//        查询用户id
        List<JSONObject> select2 = DBUtil.select("prod-customer-查询会员基本信息", new ContentDTO("customerStationCode", customerStationCode));
        for (JSONObject o: select2) {
            OpsMembershipInfo membershipInfo = new OpsMembershipInfo();
            membershipInfo.setDiscountActualPrice(o.getString("discount_actual_price"));
            membershipInfo.setMembershipTemplateId(o.getString("membership_template_id"));
            membershipInfo.setMembershipTemplatePriceId(o.getString("membership_template_price_id"));
            membershipInfo.setPriceName(o.getString("price_name"));
            membershipInfo.setStationCode(o.getString("station_code"));
            membershipInfo.setTemplateNameZh(o.getString("template_name_zh"));
            membershipInfoList.add(membershipInfo);
        }
        opsMembershipChange.setMembershipInfoList(membershipInfoList);

        return opsMembershipChange;
    }
}
